<template>
  <u-upload
      :fileList="fileList"
      @afterRead="afterRead"
      @delete="deletePic"
      name="1"
      multiple
      :maxCount="props.maxCount"
      :width="props.width"
      :height="props.height"
  ></u-upload>
</template>

<script setup lang="ts">
import {ref} from "vue"
import * as Upload from '@/utils/Upload.js'

const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  width: {
    type: Number,
    default: () => 80
  },
  height: {
    type: Number,
    default: () => 80
  },
  maxCount: {
    type: Number,
    default: () => 3
  },
})

const fileList = ref<any>([])
// 删除图片
const deletePic = (event) => {
  fileList.value.splice(event.index, 1)
}
// 新增图片
let afterRead = async (event) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  let type = event.file[0].type
  if (type != 'image') {
    uni.showToast({
      title: '请选择正确的图片格式',
      icon: 'none'
    })
    return
  }

  let lists = [].concat(event.file)
  let fileListLen = fileList.value.length
  lists.map((item) => {
    fileList.value.push({
      ...item,
      status: 'uploading',
      message: '上传中'
    })
  })
  for (let i = 0; i < lists.length; i++) {
    const result = await Upload.uploadFilePromise(lists[i].url)
    if (!result.code) {
      let item = fileList.value[fileListLen]
      fileList.value.splice(fileListLen, 1, Object.assign(item, {
        status: 'success',
        message: '',
        url: result?.data?.pathUrl || ''
      }))
      let fileArr = fileList.value.map((item) => item.url)
      emit('update:modelValue', fileArr)
      fileListLen++
    } else {
      uni.showToast({
        title: `上传失败! 错误码:【${result.code}】`,
        icon: 'none'
      })
      deletePic(fileListLen)
    }
  }
}
</script>
